<!-- src/pages/cart/tab-cart.vue -->
<script setup lang="ts">
import XtxGuess from '@/components/XtxGuess.vue'
import { onShow } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores'
import { changeSelectedAllApi, delCartApi, getCartListApi, updateCartApi } from '@/api/cart.ts'
import { computed, ref } from 'vue'
import type { CartItem } from '@/types/cart'
import vkDataInputNumberBox from '@/components/vk-data-input-number-box/vk-data-input-number-box.vue'
import debounce from 'lodash.debounce'
import { useGuessList } from '@/composables/useGuessList.ts'

const memberStore = useMemberStore()

const cartList = ref<CartItem[]>([])
const getCartList = async () => {
  const res = await getCartListApi()
  cartList.value = res.result
}

onShow(() => {
  if (memberStore.profile) getCartList()
})

const delCart = async (skuId: string) => {
  uni.showModal({
    title: '确定要删除吗？',
    success: async (res) => {
      if (res.confirm) {
        await delCartApi({ ids: [skuId] })
        getCartList()
      }
    },
  })
}

// 防抖函数，短时间多次点击数量会变化，同时视图可以正常变化，但是只有最后一次会发请求
const debouncedUpdateCart = debounce(
  (skuId: string, data: { selected?: boolean; count?: number }) => {
    updateCartApi(skuId, data)
  },
  500,
)

// 修改购物车商品数量
const changeNum = (e: { index: string; value: number }) => {
  debouncedUpdateCart(e.index, { count: e.value })
}

// 修改购物车商品选中状态
const changeSelected = (item: CartItem) => {
  item.selected = !item.selected
  debouncedUpdateCart(item.skuId, { selected: item.selected })
}

// 全选框状态
const isCheckedAll = computed(() => {
  // 购物车为空时，返回 false，因为空数组的 every 结果是 true，也就是说空数组的全选框状态是 true，不对
  // 手动返回 false
  if (!cartList.value.length) return false
  return cartList.value.every((item) => item.selected)
})

// 防抖函数，短时间多次点击全选框会变化，同时视图可以正常变化，但是只有最后一次会发请求
const debounceChangeSelectedAll = debounce((val: boolean) => {
  changeSelectedAllApi({ selected: val })
}, 500)

const changeSelectedAll = () => {
  // 新的全选框状态
  const newSelected = !isCheckedAll.value

  // 前端更新
  cartList.value.forEach((item) => {
    item.selected = newSelected
  })

  // 后端更新
  debounceChangeSelectedAll(newSelected)
}

// 使用计算属性自动追踪依赖
const selectedCart = computed(() => {
  if (!cartList.value.length)
    return {
      list: [],
      count: 0,
      money: '0.00',
    }
  // 选中的商品列表
  const selectedCartList = cartList.value.filter((item) => item.selected)
  return {
    list: selectedCartList,
    count: selectedCartList.reduce((sum, item) => sum + item.count, 0),
    money: selectedCartList.reduce((sum, item) => sum + item.nowPrice * item.count, 0).toFixed(2),
  }
})

// 猜你喜欢下拉加载
const { guessRef, onScrolltolower } = useGuessList()

const goCreate = () => {
  if (!selectedCart.value.list.length) return uni.showToast({ title: '请选择商品', icon: 'none' })

  // 跳转到订单确认页面
  uni.navigateTo({
    url: '/pagesOrder/pages/create/create',
  })
}
</script>

<template>
  <scroll-view scroll-y class="scroll-view" @scrolltolower="onScrolltolower">
    <!-- 已登录: 显示购物车 -->
    <template v-if="memberStore.profile">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="cartList.length">
        <!-- 优惠提示 -->
        <view class="tips">
          <text class="label">满减</text>
          <text class="desc">满1件, 即可享受9折优惠</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="item in cartList" :key="item.skuId" class="cart-swipe">
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text
                class="checkbox"
                :class="{ checked: item.selected }"
                @tap="changeSelected(item)"
              ></text>
              <navigator
                :url="`/pages/goods/goods?id=${item.id}`"
                hover-class="none"
                class="navigator"
              >
                <view class="container">
                  <!-- #ifdef MP-WEIXIN -->
                  <image mode="aspectFill" class="picture" :src="item.picture" lazy-load></image>
                  <!-- #endif -->
                  <!-- #ifdef H5 || APP-PLUS -->
                  <img :src="item.picture" alt="" class="picture" loading="lazy" />
                  <!-- #endif -->
                  <view class="meta">
                    <view class="name ellipsis">{{ item.name }}</view>
                    <view class="attrsText ellipsis">{{ item.attrsText }}</view>
                    <view class="price">{{ item.nowPrice }}</view>
                  </view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <vk-data-input-number-box
                  v-model="item.count"
                  :min="1"
                  :max="item.stock"
                  :index="item.skuId"
                  @change="changeNum"
                ></vk-data-input-number-box>
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <button class="button delete-button" @tap="delCart(item.skuId)">删除</button>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="/static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef"></XtxGuess>
  </scroll-view>
  <!-- 吸底工具栏 -->
  <view v-if="memberStore.profile && cartList.length" class="toolbar">
    <text class="all" :class="{ checked: isCheckedAll }" @tap="changeSelectedAll">全选</text>
    <text class="text">合计:</text>
    <text class="amount">{{ selectedCart.money }}</text>
    <view class="button-grounp">
      <view
        class="button payment-button"
        :class="{ disabled: selectedCart.list.length === 0 }"
        @tap="goCreate"
      >
        去结算({{ selectedCart.count }})
      </view>
    </view>
  </view>
</template>

<style lang="scss">
/* #ifdef MP-WEIXIN */
// 根元素，box-sizing 保证高度不超出 100vh
:host {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f7f7f8;
  box-sizing: border-box;
}

/* #endif */

// 滚动容器
.scroll-view {
  flex: 1;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #fff;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      background-color: #27ba9b;
      margin-right: 10rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;

    .container {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e6cd';
        font-family: 'erabbit' !important;
        font-size: 40rpx;
        color: #444;
      }

      &.checked::before {
        content: '\e6cc';
        color: #27ba9b;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: flex-start;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-bottom: 10rpx;
      font-size: 24rpx;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 15rpx;
      right: 5rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    padding: 6px;
    line-height: 1.5;
    color: #fff;
    font-size: 26rpx;
    border-radius: 0;
  }

  .delete-button {
    background-color: #cf4444;
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;

  .image {
    width: 400rpx;
    height: 281rpx;
  }

  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }

  .button {
    width: 240rpx;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #27ba9b;
  }
}

// 吸底工具栏
.toolbar {
  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;

  .all {
    margin-left: 25rpx;
    font-size: 14px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'erabbit' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6cc';
    color: #27ba9b;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 32rpx;
    color: #444;
    font-size: 14px;
  }

  .amount {
    font-size: 14px;
    color: #cf4444;

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background-color: #27ba9b;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
